package com.tmall.wireless.vaf.virtualview.view.scroller;

import com.alibaba.fastjson.JSONArray;
import com.tmall.wireless.vaf.Log;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.StackLayout;
import ohos.utils.PlainArray;
import com.tmall.wireless.vaf.framework.VafContext;
import com.tmall.wireless.vaf.framework.cm.ContainerService;
import com.tmall.wireless.vaf.virtualview.core.IContainer;
import com.tmall.wireless.vaf.virtualview.core.Layout;
import com.tmall.wireless.vaf.virtualview.core.ViewBase;
import com.tmall.wireless.vaf.virtualview.event.EventData;
import com.tmall.wireless.vaf.virtualview.event.EventManager;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class ScrollerRecyclerViewAdapter extends BaseItemProvider {
    private final static String WATERFALL = "waterfall";
    private final static String STICKY_TOP = "stickyTop";
    private int mAutoRefreshThreshold = 5;

    private String mStickyTopType;

    private VafContext mContext;
    private ScrollerImp mScrollerImp;
    private ContainerService mContainerService;
    private JSONArray mFastData = new JSONArray();
    private HashMap<Integer, Component> views = new HashMap<>();

//    private int mStickyTopPos = 1000000;

    private ConcurrentHashMap<String, Integer> mTypeMap = new ConcurrentHashMap<>();
    private PlainArray<String> mId2Types = new PlainArray<>();
    private AtomicInteger mTypeId = new AtomicInteger(0);

    public ScrollerRecyclerViewAdapter(VafContext vafContext, ScrollerImp scrollerImp) {
        mContext = vafContext;
        mScrollerImp = scrollerImp;
        mContainerService = mContext.getContainerService();
    }


    public void setData(Object data) {
        if (null != data && data instanceof JSONArray) {
            mFastData = (JSONArray) data;
        } else {
            Log.i("setData failed:" + data);
        }

//        mStickyTopPos = 1000000;
    }

    public void appendData(Object data) {
        if (data instanceof JSONArray) {
            JSONArray arr = (JSONArray) data;

            if (null == mFastData) {
                mFastData = arr;
                notifyDataChanged();
            } else {
                int startPos = mFastData.size();
                int len = arr.size();
                for (int i = 0; i < len; ++i) {
                    mFastData.add(arr.get(i));
                }
                notifyDataSetItemRangeChanged(startPos, len);
            }
        } else {
            Log.i("appendData failed:" + data);
        }
    }


    @Override
    public int getCount() {
        int size = mFastData.size();
        return size;
    }

    public HashMap<Integer, Component> getViews() {
        return views;
    }

    @Override
    public Object getItem(int i) {
        return views.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {

        String type = mId2Types.get(getViewType(i)).get();
        Log.i("ScrollerRecyclerViewAdapter.getComponent([i, component, componentContainer]):95     加载条目:" + i);
        Component container = mContainerService.getContainer(type);
        if (type .equals(mStickyTopType) ) {
            Layout.Params p = ((IContainer) container).getVirtualView().getComLayoutParams();
            StackLayout stackLayout = new StackLayout(mContext.forViewConstruction());

            stackLayout.addComponent(container, p.mLayoutWidth, p.mLayoutHeight);

            container = stackLayout;
        }

        ViewBase viewBase = ((IContainer) container).getVirtualView();
        viewBase.setVData(mFastData.get(i));
        if (viewBase.supportExposure()) {
            mContext.getEventManager().emitEvent(EventManager.TYPE_Exposure, EventData.obtainData(mContext, viewBase));
        }

        int threshold = mAutoRefreshThreshold;
        int length = 0;
        length = mFastData.size();
        if (length < mAutoRefreshThreshold) {
            threshold = 2;
        }
        if (i + threshold == length) {
            // load new data
            mScrollerImp.callAutoRefresh();
        }
        views.put(i, container);
        return container;
    }


    public void setAutoRefreshThreshold(int threshold) {
        mAutoRefreshThreshold = threshold;
    }


    public void destroy() {
        mScrollerImp = null;
        mFastData = null;
        mContext = null;
        mContainerService = null;
    }

    private int getViewType(int position) {
        if (null != mFastData) {
            com.alibaba.fastjson.JSONObject obj = mFastData.getJSONObject(position);
            String type = obj.getString(ViewBase.TYPE);
            if (obj.getIntValue(STICKY_TOP) > 0) {
                mStickyTopType = type;
            }
            if (mTypeMap.containsKey(type)) {
                return mTypeMap.get(type).intValue();
            } else {
                int newType = mTypeId.getAndIncrement();
                mTypeMap.put(type, newType);
                mId2Types.put(newType, type);
                return newType;
            }
        }
        return -1;
    }

}
